package com.kexun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kexun.annotation.AddToken;
import com.kexun.annotation.CheckToken;
import com.kexun.annotation.LoginManage;
import com.kexun.common.utils.DingUtils;
import com.kexun.common.utils.ResponseEntity;
import com.kexun.controller.base.BaseController;
import com.kexun.entity.DO.Manage;
import com.kexun.entity.DO.Permission;
import com.kexun.entity.VO.Menu;
import com.kexun.service.ManageService;
import com.kexun.shiro.IncorrectCaptchaException;
import com.kexun.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private ManageService manageService;
    @Value("${server.port}")
    private int port;


    @ResponseBody
    @PostMapping("upload")
    public Map<String, Object> bachInput(MultipartFile file) throws IOException {
        saveMusic(file);
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("code", 0);
        resMap.put("msg", "");
        return resMap;
    }

    public void saveMusic(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        System.out.println("保存:" + originalFilename);
        file.transferTo(new File("G:\\采集\\" + originalFilename));
    }


    //钉钉登录
    @RequestMapping("dingLogin")
    public String dingLogin(String code, String state, HttpSession session) {
        String dingInfo = DingUtils.getDingInfo(code);
        JSONObject dingRes = JSON.parseObject(dingInfo);
        if (dingRes.containsKey("user_info")) {
            JSONObject userInfo = dingRes.getJSONObject("user_info");
            String nick = userInfo.getString("nick");
            String openid = userInfo.getString("openid");
            Manage manage = manageService.findByOpenId(openid);
            if (manage == null) {
                manage = new Manage();
                manage.setOpenId(openid);
                manage.setPassword(openid);
                manage.setNickName(nick);
                manage.setManageName("钉钉用户" + nick);
                manage.setIsLock(0);
                manage.setRoleId(1);//管理员
                manageService.register(manage);
                manage = manageService.findUserById(manage.getId());//要获取角色信息
            }
            //shiro登录
            try {
                UsernamePasswordToken token = new UsernamePasswordToken(manage.getManageName(), openid.toCharArray(), false, "127.0.0.1");
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);//正常验证
                session.setAttribute("manage", manage);
                HashSet<String> permissionSet = new HashSet<>();
                List<Permission> permissionList = manage.getRole().getPermissionList();
                for (Permission permission : permissionList) {
                    permissionSet.add(permission.getPermissionName());
                }
                session.setAttribute("permissionSet", permissionSet);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("登录失败");
            }

        }
        System.out.println(dingInfo);
        return "redirect:/index";
    }

    @AddToken(name = "ps-token")
    @GetMapping("updPassword")
    public String updPassword() {
        return "updatePassword";
    }

    @CheckToken(name = "ps-token")
    @ResponseBody
    @PostMapping("updPassword")
    public ResponseEntity updPassword(String oldPassword, String newPassword) {
        manageService.updatePassword(oldPassword, newPassword, manage);
        return new ResponseEntity().success();
    }


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@LoginManage Manage manage) {
        if (manage != null) {
            return "redirect:/";
        }
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity login(HttpServletRequest request) {
        Object exception = request.getAttribute("shiroLoginFailure");
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.isInstance(exception)) {
                msg = "账号不存在";
            } else if (IncorrectCredentialsException.class.isInstance(exception)) {
                msg = "密码不正确";
            } else if (IncorrectCaptchaException.class.isInstance(exception)) {
                msg = "验证码不正确";
            } else if (DisabledAccountException.class.isInstance(exception)) {
                msg = "用户已被禁用";
            } else {
                msg = "未知错误" + exception.toString();
            }
            return new ResponseEntity().error(msg);
        }

        return new ResponseEntity().success();
    }


    @RequestMapping(method = RequestMethod.GET, value = "/logout")
    public String loginOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login";
    }


    //主页
    @GetMapping({"index", "/"})
    public String index(Model model, @LoginManage Manage manage) {
        List<Permission> permissionList = manage.getRole().getPermissionList();
        List<Menu> menu = createMenu(permissionList, 0);
        model.addAttribute("munu", menu);
        model.addAttribute("nickName", manage.getNickName());
        model.addAttribute("manageName", manage.getManageName());
        model.addAttribute("port", port);
        return "index";
    }

    @ResponseBody
    @GetMapping({"/menu"})
    public ResponseEntity index(@LoginManage Manage manage) {
        List<Permission> permissionList = manage.getRole().getPermissionList();
        List<Menu> menu = createMenu(permissionList, 0);
        return new ResponseEntity().success("成功", menu);
    }


    private List<Menu> createMenu(List<Permission> permissionList, int pid) {
        List<Menu> list = new ArrayList<Menu>();
        for (Permission permission : permissionList) {
            if (permission.getIsButton() == 0) {
                if (permission.getParentId() == pid) {
                    Menu menu = new Menu();
                    menu.setId(permission.getId());
                    menu.setUrl(permission.getPermissionName());
                    menu.setMenuName(permission.getMenuName());
                    menu.setIcon(permission.getMenuIcon());
                    if (permission.getCount() > 0) {
                        menu.setChildren(createMenu(permissionList, permission.getId()));
                    }
                    list.add(menu);
                }
            }
        }
        return list;
    }




}
